package com.steve.xfood.controller;

import com.lly835.bestpay.model.PayResponse;
import com.steve.xfood.dto.OrderDTO;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.exception.XFoodException;
import com.steve.xfood.service.OrderService;
import com.steve.xfood.service.WeChatPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @author steve
 * @date 2020/5/15 6:27 上午
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class WeChatPayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WeChatPayService weChatPayService;

    /**
     * 发起支付订单
     * Best-Pay-Sdk使用方式可以参考文档：
     * https://github.com/Pay-Group/best-pay-sdk/blob/develop/doc/use.md
     *
     * 手机微信发起订单支付的url：
     * http://proxy.springboot.cn/pay?openid=oTgZpwdZi_KC40hZHU-YmlWogkHU&orderId=1588936402833305352&returnUrl=http://www.imooc.com
     * @return 重定向url
     */
    @GetMapping("/create")
    @ResponseBody
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String, Object> map) {
        //获取订单数据
        OrderDTO orderDTO = orderService.findOrderById(orderId);
        if (orderDTO == null) {
            log.info("【微信支付】 订单不存在 orderId={}", orderId);
            throw new XFoodException(ResultEnum.ORDER_NOT_EXIST);
        }
        //发起订单支付
        PayResponse payResponse = weChatPayService.create(orderDTO);
        map.put("payResponse",payResponse);
        try {
            //需要把前端传递过来的returnUrl进行解码，不然无法跳转到订单详情页
            String returnUrlDecode = URLDecoder.decode(returnUrl, "UTF-8");
            map.put("returnUrl", returnUrlDecode);
            log.info("【微信支付】 returnUrl={}", returnUrlDecode);
        } catch (UnsupportedEncodingException e) {
            log.error("【微信支付】{}", e);
            throw new XFoodException(ResultEnum.WECHAT_PAY_ERROR);
        }
        return new ModelAndView("pay/create",map);
    }


    /**
     * 微信支付异步通知
     * 商户根据此通知来来修改订单状态
     * @param notifyData 前端传递，包括return_code和return_msg
     * @return
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        //获取微信异步通知
        weChatPayService.notify(notifyData);

        //下单成功后，告诉微信通知处理结果，这样微信就不会一直发送异步通知
        return new ModelAndView("pay/success");
    }
}
